package com.xwwx.common;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;



public class StringUtil {
	/**
	 * Check whether a String is Double.
	 * 
	 * @param str
	 *            the String to be checked.
	 * @param isNegative
	 *            whether the double is negative.
	 * @return boolean if is double and fit negative or positive then reurn
	 *         true.
	 */
	public static boolean isValidDouble(String str, boolean isNegative) {
		double dblString;

		if (str == null) {
			return false;
		}
		try {
			dblString = Double.valueOf(str.trim()).doubleValue();
		} catch (Exception exc) {
			return false;
		}

		if ((!isNegative) && dblString < 0) {
			return false;
		}

		return true;

	}

	/**
	 * Check whether a String is a numeric.
	 * 
	 * @param str
	 *            the String to be checked.
	 * @return boolean if it is numeric then reurn true.
	 */
	public static boolean isNumeric(String str) {
		int strLen;
		int i;

		if (str == null)
			return false;

		strLen = str.length();

		if (strLen < 1)
			return true;

		for (i = 0; i < strLen; i++) {
			if (!Character.isDigit(str.charAt(i))
					&& !Character.isWhitespace(str.charAt(i)))
				return false;
		}

		return true;
	}

	public static boolean isAlphabet(String str) {
		int strLen;
		int i;

		if (str == null)
			return false;

		strLen = str.length();

		if (strLen < 1)
			return true;

		for (i = 0; i < strLen; i++) {
			if (!Character.isLetter(str.charAt(i))
					&& !Character.isWhitespace(str.charAt(i)))
				return false;
		}

		return true;
	}

	public static boolean checkStringFormat(String str, String format) {
		boolean result = true;
		char thisChar;
		char formatChar;

		if (str.length() != format.length())
			return false;

		for (int i = 0; i < str.length(); i++) {
			formatChar = format.charAt(i);
			thisChar = str.charAt(i);
			switch (formatChar) {
			case 'A':
				if (!((thisChar >= 'A' && thisChar <= 'Z') || (thisChar >= 'a' && thisChar <= 'z')))
					result = false;
				break;
			case '9':
				if (!(thisChar >= '0' && thisChar <= '9'))
					result = false;
				break;
			case '$':
				if (((thisChar >= 'A' && thisChar <= 'Z') || (thisChar >= 'a' && thisChar <= 'z'))
						|| (thisChar >= '0' && thisChar <= '9'))
					result = false;
				break;
			default:
				result = false;
			}
		}
		return result;
	}

	public static boolean isAlphabet(char c) {
		if (getASCIICode(c) >= 97 && getASCIICode(c) <= 122)
			return true;
		if (getASCIICode(c) >= 65 && getASCIICode(c) <= 90)
			return true;
		return false;
	}

	public static boolean isNumeric(char c) {
		if (getASCIICode(c) >= 48 && getASCIICode(c) <= 57)
			return true;
		return false;
	}

	public static int getASCIICode(char c) {
		return (int) c;
	}

	public static int getIntValue(char c) {
		String s = String.valueOf(c);
		return Integer.parseInt(s);
	}

	public static boolean checkEmail(String strMailAddress) {
		boolean result = true;
		if (strMailAddress == null)
			return false;
		if (strMailAddress.equals(""))
			return true;
		if (strMailAddress.indexOf("@") < 0 || strMailAddress.indexOf(".") < 0)
			return false;
		for (int i = 0; i < strMailAddress.length(); i++) {
			if (!Character.isWhitespace(strMailAddress.charAt(i))
					&& !Character.isLetterOrDigit(strMailAddress.charAt(i))
					&& !(strMailAddress.charAt(i) == '@')
					&& !(strMailAddress.charAt(i) == '.')
					&& !(strMailAddress.charAt(i) == '_'))
				result = false;
		}
		return result;
	}

	public static boolean checkTelNumber(String strTelNumber) {
		boolean result = true;
		if (strTelNumber == null)
			return false;
		if (strTelNumber.equals(""))
			return true;
		for (int i = 0; i < strTelNumber.length(); i++) {
			if (!Character.isDigit(strTelNumber.charAt(i))
					&& !(strTelNumber.charAt(i) == '-')
					&& !(strTelNumber.charAt(i) == '(')
					&& !(strTelNumber.charAt(i) == ')'))
				result = false;
		}
		return result;
	}

	/**
	 * Replace the "'" in a String to "''"
	 * 
	 * @param str
	 *            the String to be replaced;
	 * @return the replaced String.
	 */
	public static String replaceQuotationMarks(String str) {
		if (str == null)
			return str;
		StringBuffer strBuf = new StringBuffer("");
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			if (c == '\'') {
				strBuf.append('\'');
				strBuf.append('\'');
			} else {
				strBuf.append(c);
			}
		}
		return strBuf.toString();
	}

	/**
	 * 功能：屏蔽html字符
	 */
	public static String parseHtml(String str) {
		if (str == null || str.length() == 0) {
			return str;
		}
		char[] aryToParse = str.toCharArray();
		StringBuffer strBf = new StringBuffer();
		char c;
		for (int i = 0; i < aryToParse.length; i++) {
			c = aryToParse[i];
			switch (c) {
			case '<':
				strBf.append("&lt;");
				break;
			case '>':
				strBf.append("&gt;");
				break;
			case '&':
				strBf.append("&amp;");
				break;
			case '"':
				strBf.append("&quot;");
				break;
			default:
				strBf.append(c);
			}
		}
		return strBf.toString();
	}

	// replace ' to ''
	public static String parseQuoter(String str) {
		return str.replaceAll("\'", "\'\'");
	}

	public static String getIdxValue(String srcStr, String dividStr, int idx) {
		int i = 0;
		String result = "";
		while (i <= idx) {
			int idx1 = srcStr.indexOf(dividStr);
			if (idx1 == -1) {
				result = srcStr;
				break;
			}
			result = srcStr.substring(0, idx1);
			srcStr = srcStr.substring(idx1 + 1, srcStr.length());
			i = i + 1;
		}
		return result;

	}

	// 将后台提交的文章空格,回车替换成网页上的格式
	public static String getHtmlStr(String str) {
		String temstr = "";
		if (str.length() > 0) {
			temstr = str.trim();
			temstr = temstr.replaceAll(" ", "&nbsp;");
			temstr = temstr.replaceAll("\n", "<br>");
			temstr = temstr.replaceAll("\r", "");
		}
		return temstr;
	}

	// 将传过来的字符串过滤,如果为空返回""
	public static String getIfNull(String str) {
		if (str == null || str.equalsIgnoreCase("null")) {
			return "";
		} else {
			return str.trim();
		}
	}

	/**
	 * Check whether a String is Empty.
	 * 
	 * @param str
	 *            the String to be checked.
	 * @return boolean if it is empty(null or empty sstring) then reurn true.
	 */
	public static boolean isEmpty(String str) {
		return str == null || str.trim().equals("")
				|| str.trim().equalsIgnoreCase("null");
	}

	/**
	 * Check a string null or blank.
	 * 
	 * @param param
	 *            string to check
	 * @return boolean
	 */
	public static boolean nullOrBlank(String param) {
		return (param == null || param.length() == 0 || param.trim().equals("")) ? true
				: false;
	}

	public static String notNull(String param) {
		return param == null ? "" : param.trim();
	}

	public static String nullOrBlankResult(String param) {
		return (param == null || param.trim().length() == 0 || param.trim()
				.equals("")) ? "" : param.trim();
	}

	public static String toISOread(Object str) {
		try {
			if (str == null)
				return null;
			return (new String(str.toString().getBytes("ISO-8859-1"), "gb2312"));
		} catch (java.io.UnsupportedEncodingException ex) {
			return (null);
		}
	}

	public static String toISOwrite(Object str) {
		try {
			if (str == null)
				return null;
			return (new String(str.toString().getBytes("gb2312"), "ISO-8859-1"));
		} catch (java.io.UnsupportedEncodingException ex) {
			return (null);
		}
	}

	public static final String getIDCard_18bit(String id) {
		// 若是15位，则转换成18位；否则直接返回ID
		if (15 == id.length()) {
			final int[] W = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4,
					2, 1 };
			final String[] A = { "1", "0", "X", "9", "8", "7", "6", "5", "4",
					"3", "2" };
			int i, j, s = 0;
			String newid;
			newid = id;
			newid = newid.substring(0, 6) + "19"
					+ newid.substring(6, id.length());
			for (i = 0; i < newid.length(); i++) {

				j = Integer.parseInt(newid.substring(i, i + 1)) * W[i];
				s = s + j;
			}
			s = s % 11;
			newid = newid + A[s];

			return newid;
		} else {
			return id;
		}

	}

	public static String getBirthDateFromCard(String cardNumber) throws Exception{
		String card = cardNumber.trim();
		String year;
		String month;
		String day;
		if (card.length() == 18) { // 处理18位身份证
			year = card.substring(6, 10);
			month = card.substring(10, 12);
			day = card.substring(12, 14);
		} else { // 处理非18位身份证
			year = card.substring(6, 8);
			month = card.substring(8, 10);
			day = card.substring(10, 12);
			year = "19" + year;
		}
		if (month.length() == 1) {
			month = "0" + month; // 补足两位
		}
		if (day.length() == 1) {
			day = "0" + day; // 补足两位
		}
		return year + "-" + month + "-" + day;
	}

	public static String getSexFromCard(String cardNumber) {
		String Aac004_AAC004_MALE = "01";
		String Aac004_AAC0004_FEMALE = "02";
		String inputStr = cardNumber.toString();
		int sex;
		if (inputStr.length() == 18) {
			sex = inputStr.charAt(16);
			if (sex % 2 == 0) {
				return Aac004_AAC0004_FEMALE;
			} else {
				return Aac004_AAC004_MALE;
			}
		} else {
			sex = inputStr.charAt(14);
			if (sex % 2 == 0) {
				return Aac004_AAC0004_FEMALE;
			} else {
				return Aac004_AAC004_MALE;
			}
		}
	}

	public static java.sql.Date getBirthFromCard(String cardNumber) throws Exception{
		String birthString = getBirthDateFromCard(cardNumber);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		java.sql.Date birthDate = new java.sql.Date(new Date().getTime());
		// 将字符串转换为Date
		try {
			Date date = df.parse(birthString);
			birthDate = new java.sql.Date(date.getTime());
		} catch (ParseException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
		return birthDate;

	}

	public static int getAge(String IDCardNum) {
		Calendar cal1 = Calendar.getInstance();
		Calendar today = Calendar.getInstance();
		// 如果身份证15位则将其转化为18位
		if (IDCardNum.length() == 15)
			IDCardNum = getIDCard_18bit(IDCardNum);
		cal1.set(Integer.parseInt(IDCardNum.substring(6, 10)), Integer
				.parseInt(IDCardNum.substring(10, 12)), Integer
				.parseInt(IDCardNum.substring(12, 14)));
		return getYearDiff(today, cal1);
	}

	public static int getYearDiff(Calendar cal, Calendar cal1) {
		int m = (cal.get(cal.MONTH)) - (cal1.get(cal1.MONTH));
		int y = (cal.get(cal.YEAR)) - (cal1.get(cal1.YEAR));
		return (y * 12 + m) / 12;
	}

	public static void main(String args[]) throws Exception{
	     System.out.println(getBirthDateFromCard("512223741208297"));
	     System.out.println(getBirthDateFromCard("21042319771103001X"));
	     System.out.println(getAge("512223741208297"));
	        
	     System.out.println(getSexFromCard("21042319771103001X"));
	     System.out.println(getIDCard_18bit("510107050805011"));
	}
}